#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include "Controller.h"

using namespace std;

ControllerImp::ControllerImp(void)
#ifdef DEBUG_EVPROC
: EventProcessorImp(true,"Controller") // comment to remove debug
#endif
{
  
  // register the message function
  RegisterMessageProcessor(DieMessage::type, &Die, 0 /* priority */);

  RegisterMessageProcessor(CreatedDecrypterMessage::type, &Created, 1 /* priority */);
  
  RegisterMessageProcessor(DoneMessage::type, &DecryptionDone, 2 /* priority */);

  RegisterMessageProcessor(DecryptersDoneMessage::type, &Finished, 3 /* priority */);
  currentBlock = 0;

  Initialize();
	
}

void ControllerImp::SendBlock(EventProcessor& decrypter){
 
	
  EventProcessor myInterfClone;
  myInterfClone.CopyFrom(myInterface);

  DecryptMessage_Factory(decrypter, currentBlock, cipherText[currentBlock], myInterfClone);
  ++currentBlock;
}

void ControllerImp::Initialize(){
	string str("the football world cup is going on in south africa");
	string buf;
	stringstream oss(str);
	
	for(int i =0;oss>>buf;++i){
		cipherText[i] = buf;
	}
}
void ControllerImp::ExtractInfo(string plain){

	int xblock;
	string xPlain;
	xPlain = plain.substr(1);
	xblock = atoi(&plain.at(0));
	plainText[xblock] = xPlain;
	cout<<"Plain Text now : "<<plainText[xblock]<<endl;
}


MESSAGE_HANDLER_DEFINITION_BEGIN(ControllerImp, Finished, DecryptersDoneMessage)
	evProc.Seppuku();	

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(ControllerImp, Created, CreatedDecrypterMessage)
	EventProcessor decrypter;
	decrypter.CopyFrom(msg.sender);
	evProc.SendBlock(decrypter);

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(ControllerImp, DecryptionDone, DoneMessage)
	
	evProc.plainText[msg.id] = msg.plain;

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(ControllerImp, Die, DieMessage)
	
	cout<<"EveryBody is Done !!! "<<endl;
	for(int i = 0;i<10;++i)
		cout<<evProc.plainText[i]<<endl;
	evProc.EventProcessorImp::processDieMessage(evProc,msg);
	cout<<"The Correct Outcome : "<<endl;
	cout<<"THE FOOTBALL WORLD CUP IS GOING ON IN SOUTH AFRICA"<<endl;

MESSAGE_HANDLER_DEFINITION_END
